package zxj.weixin.mp.service;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zxj.weixin.mp.api.UserApi;
import zxj.weixin.mp.domain.Account;
import zxj.weixin.mp.domain.User;
import zxj.weixin.mp.domain.message.SubscribeEventMsg;
import zxj.weixin.mp.mapper.UserMapper;
import zxj.weixin.utils.MapUtils;

/**
 * 微信公众号用户Service
 * 
 * @author zhuxuejiang
 *
 */
@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AccountService accountService;

	@Autowired
	private WeixinService weixinService;

	/**
	 * 关注微信公众号
	 * 
	 * @param msg 微信关注事件推送消息
	 * @throws Exception
	 */
	public void subscribe(SubscribeEventMsg msg) throws Exception {
		// 判断消息对象是否为空
		if (null == msg) {
			return;
		}

		// 判断wxId和openid是否为空
		String wxId = msg.getToUserName();
		String openid = msg.getFromUserName();
		if (StringUtils.isBlank(wxId) || StringUtils.isBlank(openid)) {
			return;
		}

		// 判断微信公众号是否存在
		Account account = accountService.getByWxId(wxId);
		if (null == account) {
			return;
		}
		String appId = account.getAppId();

		// 判断accessToken是否为空
		String accessToken = weixinService.getAccessToken(appId);
		if (StringUtils.isBlank(accessToken)) {
			return;
		}

		// 调用微信接口获取用户信息
		Map<String, Object> map = UserApi.getUserInfo(accessToken, openid);
		if (null == map) {
			return;
		}

		map.remove("tagid_list");
		User user = (User) MapUtils.map2Object(MapUtils.keyLowerUnderScore2LowerCamel(map), User.class);
		if (null != user) {
			user.setAppId(appId);
			user.setSubscribeTime(new Date());

			// 判断用户是否存在
			User oldUser = userMapper.selectByOpenid(appId, openid);
			if (null == oldUser) {
				userMapper.insertSelective(user);
			} else {
				user.setId(oldUser.getId());
				userMapper.updateByPrimaryKeySelective(user);
			}

		}

	}

	/**
	 * 取消关注微信公众号
	 * 
	 * @param msg 微信取消关注事件推送消息
	 */
	public void unsubscribe(SubscribeEventMsg msg) {
		// 判断消息对象是否为空
		if (null == msg) {
			return;
		}

		// 判断wxId和openid是否为空
		String wxId = msg.getToUserName();
		String openid = msg.getFromUserName();
		if (StringUtils.isBlank(wxId) || StringUtils.isBlank(openid)) {
			return;
		}

		// 判断微信公众号是否存在
		Account account = accountService.getByWxId(wxId);
		if (null == account) {
			return;
		}

		// 判断用户是否存在
		User user = userMapper.selectByOpenid(account.getAppId(), openid);
		if (null == user) {
			return;
		}

		user.setSubscribe((byte) 0);
		user.setUnsubscribeTime(new Date());
		userMapper.updateByPrimaryKeySelective(user);
	}

}
